const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

app.use(cookieParser());

const port = `8081`;

function newGuid () {
	let guid = '';
	for (let i = 1; i <= 32; i++) {
		let n = Math.floor(Math.random() * 16.0).toString(16);
		guid += n;
		if ((i === 8) || (i === 12) || (i === 16) || (i === 20)) {
			guid += '-';
		}
	}
	return guid;
}

/**
 * 服务器端设置cookie的值，expires为0删除改cookie
 * @param {Object} res = response
 * @param {Object} cookieObj = { cookie_name: { value: '', expires: 1000 } }
 * expires 单位毫秒
 * @returns response
 */
function setCookie (res, cookieObj) {
	Object.keys(cookieObj).forEach((key) => {
		let value = cookieObj[key].value || '';
		if (value instanceof Object) {
			value = JSON.stringify(value);
		}
		let expires = cookieObj[key].expires || 0;
		res.cookie(key, value, { expires: new Date(Date.now() + expires) });
	});
	return res;
}

app.get('/setCookie', (req, res) => {
	res = setCookie(res, {
		'aaa': {
			value: {a: 122},
			expires: 900000
		}
	});
	res.end();
});

app.get('/getCookie', (req, res) => {
	console.log(req.url);
	console.log(req.cookies);
	console.log(req.cookies.aaa);
	res.end(JSON.stringify(req.cookies));
});

app.get('*', (req, res, next) => {
	res.setHeader('Access-Control-Allow-Origin', '*');
	next();
});

app.get('/index/getMore', (req, res) => {
	console.log(req.cookies);
	let guid = newGuid();
	let result = [];
	for (let i = 0, len = 10; i < len; i++) {
		let obj = {};
		let type = 0;
		switch (Math.floor(Math.random() * 10)) {
			case 2:
				type = 2;
				break;
			case 3:
				type = 3;
				break;
			case 4:
				type = 4;
				break;
			default:
				type = 1;
				break;
		}
		if (type === 1) {
			obj = {
				id: `n-${guid}-${type}-${i}`,
				avator: `http://cn.vuejs.org/images/logo.png`,
				imgUrl: Math.floor(Math.random() * 10) < 5 ? `https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1494914521275&di=8544d7da516651dbe1193b0e32b26f4e&imgtype=0&src=http%3A%2F%2Fimg2.3lian.com%2F2014%2Ff2%2F61%2Fd%2F118.jpg` : ``,
				from: '来自话题 vue.js',
				title: '建筑少女的Airbnb作业，真想住进她36㎡的艺术里',
				description: '建筑少女的Airbnb作业，真想住进她36㎡的艺术里建筑少女的Airbnb作业，真想住进她36㎡的艺术里建筑少女的Airbnb作业，真想住进她36㎡的艺术里',
				agree: `${Math.floor(Math.random() * 100)}赞同`,
				comments: `${Math.floor(Math.random() * 100)}评论`,
				goto: '',
				isFocus: Math.floor(Math.random() * 10) < 3 ? true : false,
				type: type
			};
		}
		else if (type === 2) {
			obj = {
				id: `n-${guid}-${type}-${i}`,
				avator: `http://cn.vuejs.org/images/logo.png`,
				recommends: (() => {
					let recList = [];
					for (let j = 0, recLen = 15; j < recLen; j++) {
						let recObj = {
							id: `n-${guid}-${type}-${i}-${j}`,
							avator: `http://cn.vuejs.org/images/logo.png`,
							title: `摩拜产品负责人: 共享单车,最后的赢家会是谁?`,
							name: `name-${Math.floor(Math.random() * 100)}`,
							time: `${Math.floor(Math.random() * 100)} 天后`
						};
						recList.push(recObj);
					}
					return recList;
				})(),
				type: type
			};
		}
		else if (type === 3) {
			obj = {
				id: `n-${guid}-${type}-${i}`,
				avator: `http://cn.vuejs.org/images/logo.png`,
				imgUrl: `https://gss0.bdstatic.com/94o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=0157d6998d13632701e0ca61f0e6cb89/8d5494eef01f3a293d7d9f8b9e25bc315c607c39.jpg`,
				from: '来自话题: 健身',
				title: '硬派健身：你的第一本健身书',
				author: '斌卡',
				description: '作者 斌卡 曾在 【知乎电子书】出版过《硬派健身：减肥篇》和《硬派健身：臀腿训练》，深受知友喜爱作者 斌卡 曾在 【知乎电子书】出版过《硬派健身：减肥篇》和《硬派健身：臀腿训练》，深受知友喜爱',
				agree: `${Math.floor(Math.random() * 100)}赞同`,
				comments: `${Math.floor(Math.random() * 100)}评论`,
				goto: '',
				type: type
			};
		}
		else if (type === 4) {
			obj = {
				id: `n-${guid}-${type}-${i}`,
				avator: `http://cn.vuejs.org/images/logo.png`,
				recommends: (() => {
					let recList = [];
					for (let j = 0, recLen = 15; j < recLen; j++) {
						let recObj = {
							id: `n-${guid}-${type}-${i}-${j}`,
							imgUrl: `https://gss0.bdstatic.com/94o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=0157d6998d13632701e0ca61f0e6cb89/8d5494eef01f3a293d7d9f8b9e25bc315c607c39.jpg`,
							title: `硬派健身：你的第一本健身书`,
							author: '斌卡',
							goto: ''
						};
						recList.push(recObj);
					}
					return recList;
				})(),
				type: type
			};
		}
		result.push(obj);
	}
	res.send(result);
});

app.get('/jsonpTest', (req, res) => {
	res.end('callback(' + JSON.stringify({'a': 1}) + ')');
});

app.listen(port, (err) => {
	if (err) {
		console.log(err);
		return;
	}
	console.log(`listen at: ${port}`);
});
